define(['template/translate/indexTpl','wx','wx.ajax','wx.tpl'],function(tpl,wx){
    var translate = {};
    
    function init(id){
        var t = new Date().getTime();
        $.when(
            $.ajax('/res/css/translate.css?_='+t))
        .done(function(css){
            var trans = wx.throttle(translating,300);
            $('<style type="text/css">').append(css).appendTo('head');
            $('#window-frame-translate').html(tpl.transfer);
            $('#Js-translateBtn').click(translating);
            $('#Js-translateText').keydown(trans);
        });
    }

    function translating(){
        var value = $('#Js-translateText').val();
        var t = new Date().getTime();
        if(!value) return;

        if(/^[a-zA-Z].*$/.test(value)){
            translate.type = 'en';
            wx.sendData('/translate?_='+t,'from=en&to=zh&query='+value,showResult);
        }else{
            translate.type = 'zh';
            wx.sendData('/translate?_='+t,'from=zh&to=en&query='+value,showResult);
        }
    }

    function showResult(data){
        if(data.result.error_code){
            $('#Js-result').html(data.result.reason);
        } else{
            $('#Js-result').html(wx.tpl(translate.type=='en'?tpl.en_result:tpl.ch_result,data.result)).show();
        }
    }
    
    translate.init = init;

    return translate;
});